<template>
  <view class="page">
    <fu-custom bgColor="bg-white" :isBack="true" :isBottom="true">
      <view slot="content">{{i18n['我的订单']}}</view>
    </fu-custom>
    <fu-tab :tabs="navList" :sticky="true" line-height="8" radius="80" bottom="0" :top="CustomBar" node-title="text"
      @change="tabClick" node-key="state" :current="type" current-key="type" :line-color="themeColor" :active-color="themeColor"></fu-tab>
    <!-- 订单状态栏Tab-结束 -->
		<!-- 订单列表-开始 -->
		<view class="list margin-lr-sm margin-top-sm">
			<block v-for="(item, index) in listData" :key="index">
				<order-item
					v-if="tabCurrentIndex !== 5"
					:item="item"
					:index="index"
					@showCancelReason="showCancelReason"
				></order-item>
				<afterorder-item
					v-else
					:item="item"
					:index="index"
				></afterorder-item>
			</block>
		</view>
		<!-- 订单列表-结束 -->
		<!-- 分页组件 start -->
		<fu-empty :paging-list-loaded-all="pagingListLoadedAll" :paging-list-no-list-data="pagingListNoListData"
		  :list-data-length="listDataLength" :isLoadInit='isLoadInit'></fu-empty>
		<!-- 分页组件 end -->
    <!-- 取消订单弹出层-开始 -->
    <fu-popup v-model="showPopup" mode="bottom" border-radius="24">
      <view class="cancel-order-pop">
        <view class="flex justify-between align-center" style="padding:0 32rpx;">
          <view class="text-999 text-weight-400 text-df" @click="showPopup = false">{{ i18n['取消'] }}</view>
          <view class="pop-title">{{ i18n['取消订单'] }}</view>
          <view class="text-theme text-weight-400 text-df" @click="cancelOrder()">{{ i18n['确定'] }}</view>
        </view>
        <view class="pop-count">
          <view class="tips text-sm">{{ i18n['请选择取消订单原因'] }}</view>
          <scroll-view scroll-y="true" style="max-height: 400rpx; min-height: 200rpx">
            <view class="pop-count-list">
              <view @click="onChangeReson(item, index)" class="item flex align-center justify-between"
                v-for="(item, index) in reasonList" :key="index">
                <view class="item-label">{{ item.reason }}</view>
                <image v-if="index == cancelObj.current" class="item-img" :src="imgWechatUrl+'/order/icon-select-2.png'"
                  mode="aspectFit"></image>
                <image v-else :src="imgWechatUrl+'/order/icon-select-1.png'" mode="aspectFit" class="item-img"></image>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </fu-popup>
    <!-- 取消订单弹出层-结束 -->
    <!-- 断网监测 -->
    <fu-notwork></fu-notwork>
  </view>
</template>

<script>
	import orderItem from '../../components/order-item/order-item.vue';
	import afterorderItem from '../../components/order-item/afterorder_item.vue';
	import pagingList from '@/common/mixin/paging_list.js' //引入混合开发
  /** 订单状态列表
   * all 全部订单
   * unpay 待付款订单
   * unship 待发货订单
   * unreceive 待收货订单
   * finish 待评价订单
   * refund 退款/售后
   * */
  export default {
		mixins: [pagingList],
		components: {
			orderItem,
			afterorderItem
		},
    data() {
      return {
				imgWechatUrl: this.imgWechatUrl,
        tabCurrentIndex: 0, // tab切换选中状态下标
				type: 'all', // 当前选中的状态key
        navList: [
          {
            state: 0,
            text: global.i18n['全部'],
            type: 'all'
          },
          {
            state: 1,
            text: global.i18n['待付款'],
            type: 'unpay'
          },
          {
            state: 2,
            text: global.i18n['待发货'],
            type: 'unship'
          },
          {
            state: 3,
            text: global.i18n['待收货'],
            type: 'unreceive'
          },
          {
            state: 4,
            text: global.i18n['待评价'],
            type: 'finish'
          },
          {
            state: 5,
            text: global.i18n['退款/售后'],
            type: 'refund'
          }
        ], // 订单状态切换列表
        minixPagingListsApi: global.apiUrls.getOrderList, //明细请求地址
        pageingListApiMethod: "post", //请求方法
				allowOnloadGetList: false, // 是否允许页面onload生命周期进入后立马执行getlist
        showPopup: false, // 控制取消订单弹出层是否显示
        reasonList: [], //取消原因列表
        cancelObj: {
          //订单取消对象
          current: -1, //当前原因索引
          id: '', //档原因id
          orderSn: null, //要取消的订单号
          index: null, //要取消的订单在列表中的索引
          orderItem: {} //当前订单对象
        },
      };
    },
		computed: {
			themeColor() {
				return this.$store.state.themeColor;
			}
		},
    onLoad(options) {
      this.setNavigationBarTitle(this.i18n['我的订单']);
      // 跳转订单列表未携带参数时默认全部状态
      const { type = 'all' } = options;
      // 获取当前选中状态的tab数据 包括下标，类型等
      const _item = this.navList.find(item => item.type == type);
      this.tabCurrentIndex = _item.state;
      this.type = _item.type;
			this.pagingListToggle();
      this.getReasonList();
      // 监听页面更新
      uni.$on('onPageUpdata', data=>{
				this.pagingListToggle();
			});
    },
    onUnload() {
      // 移除页面更新监听
      uni.$off('onPageUpdata');
    },
    methods: {
			/**
			 * @description  设置要请求的参数
			 * 在混入开发时，调用该方法和混入的请求参数合并在一起
			 */
			pagingListPostData() {
				if (this.tabCurrentIndex == 5) {
					this.minixPagingListsApi = global.apiUrls.getGoodsAfterSale;
				} else {
					this.minixPagingListsApi = global.apiUrls.getOrderList;
				}
			  return {
					type: this.type,
			  }
			},
			/**
			 * @description 获取取消原因列表
			 */
			getReasonList() {
			  this.$api.post(global.apiUrls.getReasonList, {
					type: 2
				}).then(res => {
					let data = res.data;
					if (data.code == 1) {
						this.reasonList = data.data;
					} else {
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					this.$message.info("服务器错误，请稍后重试");
				});
			},
			// tab切换
			tabClick(e) {
			  let index = e.index;
			  this.tabCurrentIndex = index;
			  this.type = this.navList[index].type;
			  this.pagingListToggle();
			},
			/**
			 * @description 监听页面更新的回调函数
			 * @param {Object} e = 要更新的配置参数
			 */
			onPageUpdata(e) {
				let index = e.index;
				let item = this.listData[index];
				switch (e.type) {
					case 1: // 取消订单
						if (this.tabCurrentIndex == 0) {
							item.status = -1;
							this.listData.splice(index, 1, item);
						} else {
							this.listData.splice(index, 1);
						}
						break;
					case 2: // 提醒发货
						item.is_remind.info = 1;
						this.listData.splice(index, 1, item);
						break;
					case 3: //确认收货
						if (this.tabCurrentIndex == 0) {
							item.status = 3;
							this.listData.splice(index, 1, item);
						} else {
							this.listData.splice(index, 1);
						}
						break;
					case 4: //删除订单
						this.listData.splice(index, 1);
						break;
					case 5: //评价
						if (this.tabCurrentIndex == 0) {
							item.status = 4;
							this.listData.splice(index, 1, item);
						} else {
							this.listData.splice(index, 1);
						}
						break;
					case 6: // 提交售后
						this.pagingListToggle();
						break;
					case 7: // 删除售后订单
						if (this.tabCurrentIndex == 0) {
							this.pagingListToggle();
						} else {
							this.listData.splice(index, 1);
						}
						break;
					case 8: // 付款成功
						if (this.tabCurrentIndex == 0) {
							item.status = 1;
							this.listData.splice(index, 1, item);
						} else {
							this.listData.splice(index, 1);
						}
						break;
					default:
						break;
				}
			},
      /**
       * @description 展示取消原因
       * @param {Object} item = 当前订单项对象
       * @param {Number} index = 当前订单在列表中的索引
       */
      showCancelReason(e) {
        this.cancelObj.orderSn = e.item.order_sn;
        this.cancelObj.index = e.index;
        this.cancelObj.orderItem = e.item;
        this.cancelObj.current = -1;
        this.cancelObj.id = '';
        this.showPopup = true;
      },

      /**
       * @description 取消订单
       * @param {string} sn = 订单号
       * */
      cancelOrder() {
        if (!this.cancelObj.id) return this.$message.info(this.i18n['请选择取消原因']);
        this.$api.post(global.apiUrls.postCancelOrder, {
					order_sn: this.cancelObj.orderSn,
					return_id: this.cancelObj.id
				}).then(res => {
					this.$message.info(res.data.msg);
					if (res.data.code == 1) {
						this.showPopup = false;
						this.cancelObj.id = '';
						uni.$emit('onPageUpdata', {
							type: 1, // 1: 取消订单， 2: 提醒发货， 3: 确认订单， 4: 删除订单，
							index: this.cancelObj.index,
						})
					} else {
						
					}
				}).catch(err => {
					this.$message.info('服务器错误，请稍后重试');
				});
      },

      /**
       * @description 监听切换取消原因
       * @param {Object} item = 当前原因项
       * @param {Number} index = 当前原因在列表中的索引
       */
      onChangeReson(item, index) {
        if (this.cancelObj.current == index) return false;
        this.cancelObj.current = index;
        this.cancelObj.id = item.id;
      },
      // 取消申请
      cancelAfter(item) {
        let that = this;
        if (that.is_click) return;
        this.$util.showModal({
          title: this.i18n['提示'],
          content: this.i18n['确定取消申请吗？'],
          cancelText: this.i18n['取消'],
          confirmText: this.i18n['确定'],
          success: res => {
            if (res.confirm) {
              that.$api
                .post(global.apiUrls.getGoodsAfterSaleCentel, {
                  id: item.id
                })
                .then(res => {
                  console.log(res);
                  that.$message.info(res.data.msg);
                  if (res.data.code == 1) {
                    this.$message.info("取消成功");
                  }
                })
                .catch(err => {
                  console.log('err: ' + JSON.stringify(err));
                });
            }
          }
        });
      },
      // 去售后详情
      toDetail(item) {
        this.$urouter.navigateTo({
          url: '/pages/order/afterorder/afterorder-detail/index',
          params: {
            id: item.id
          }
        })
      },
			/**
			 * @description 判断内容是否显示
			 * @param {String} arr = 要判端数组
			 * @param {String | Number} val = 要判的值
			 */
			isContentShow(arr, val) {
			  return arr.includes(val * 1);
			},
    },
  };
</script>

<style lang="scss" scoped>
  .page {
    min-height: calc(100vh - 88rpx);
  }
  // 取消订单弹出层-开始
  .cancel-order-pop {
    border-radius: 24rpx 24rpx 0 0;

    .pop-title {
      line-height: 114rpx;
      height: 114rpx;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
    }

    .pop-count {
      .tips {
        line-height: 90rpx;
        background-color: #f8f8f8;
        padding: 0 24rpx;
        color: #666;
      }

      .pop-count-list {
        padding: 32rpx 24rpx;

        .item {
          padding-bottom: 32rpx;

          .item-img {
            width: 32rpx;
            height: 32rpx;
          }
        }
      }
    }
  }

  // 取消订单弹出层-结束
</style>
